#!/usr/bin/env python
#coding=utf-8
import select, socket, Queue

server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

server_address = ('127.0.0.1', 10001)
server.bind(server_address)
server.listen(1)

#每增加一个连接直接赋值给input队列，也就是read队列
inputs = [server]
#写队列
outputs = []

#消息队列
message_queue = {}
timeout = 20

while inputs:
	#调用select方法监听队列里赋值读队列，写队列，异常队列
	readable, writeable, exceptional = select.select(inputs,outputs,inputs,timeout)
	#print '-------->', readable, writeable, exceptional
	#
	if not (readable and not writeable and not exceptional):
		print 'time out~~~'
		#break

	"""处理读队列"""
	for s in readable:
		if s is server:
			connection, client_address = s.accept()
			print 'connected from: ', client_address
			inputs.append(connection)
			message_queue[connection] = Queue.Queue()
		else:
			data = s.recv(1024)
			if data:
				print "recv ", data, 'from ', s.getpeername()
				message_queue[s].put(data)
				if s not in outputs:
					outputs.append(s)
			else:
				print 'closed ', s.getpeername()
				if s in outputs:
					outputs.remove(s)
				inputs.remove(s)
				s.close()
				del message_queue[s]

	"""处理写处理队列"""
	for s in writeable:
		try:
			next_msg = message_queue[s].get_nowait()
		except Queue.Empty:
			print 'queue is empty', s.getpeername()
			outputs.remove(s)
		else:
			print 'send msg to', s.getpeername()
			s.sendall(next_msg)

	"""处理异常"""
	for s in exceptional:
		"""如果"""
		inputs.remove(s)
		if s in outputs:
			outputs.remove(s)
		s.close()
		del message_queue[s]